<?php

namespace App\Http\Controllers\Export;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Export\Export;
use App\Models\CompetiteActivity;
use App\Models\CompetiteActivityWorksType;
use App\Models\CompetiteActivityGroup;
use App\Models\CompetiteActivityWorks;
use App\Models\UserInfo;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 线上大赛作品导出
 */
class CompetiteActivityWorksExport extends Controller
{

    public $model = null;
    public $competiteActivityModel = null;

    public function __construct()
    {
        parent::__construct();
        $this->model = new CompetiteActivityWorks();
        $this->competiteActivityModel = new CompetiteActivity();
    }


    /**
     * 大赛作品导出
     * @param type 类型  1 个人账号  2 团队账号  当前是团队查询还是个人查询
     * @param page int 当前页
     * @param limit int 分页大小
     * @param con_id int 大赛id
     * @param group_id int 团队id  
     * @param status int 是否审核 状态  1.已通过   2.未通过   3.未审核(默认)   不传为全部
     * @param type_id int 类型id
     * @param keywords string 搜索关键词(作品名称|姓名|编号)
     * @param start_time datetime 投稿时间(开始)
     * @param end_time datetime 投稿时间(截止)
     * @param sort int 排序方式  1 时间排序（默认）  2 投票排序  3 评分排序
     * @param except_ids string 需要排除的id ，多个逗号链接
     * @param is_review_score string 是否评审打分  1 已打分  2 未打分
     * @param is_add_ebook string 是否是加入电子书 1 是 
     * @param is_violate string 是否违规  1正常 2违规 
     * @param is_show string 是否显示  1显示 2不显示 
     * @param except_database_id string 排除数据库对应产品id
     * 
     * @param score_manage_id string 打分审核人id  （con_id 必须存在）
     * @param score_manage_status string 打分审核人选择状态  0 查询所有（score_manage_id 无效） 1 查看所有已选择的作品  2 查询所有未选中的作品 
     */
    public function index()
    {
        //增加验证场景进行验证
        // if (!$this->validate->scene('production_list')->check($this->request->all())) {
        //     return $this->returnApi(201,  $this->validate->getError());
        // }

        $type = $this->request->type;
        $con_id = $this->request->con_id;
        $group_id = $this->request->group_id;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = 99999;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $status = $this->request->status;
        $type_id = $this->request->type_id;
        $except_ids = $this->request->except_ids;
        $is_review_score = $this->request->is_review_score;
        $is_add_ebook = $this->request->is_add_ebook;
        $is_violate = $this->request->is_violate;
        $is_show = $this->request->is_show;
        $except_database_id = $this->request->except_database_id;
        $score_manage_id = $this->request->score_manage_id;
        $score_manage_status = $this->request->score_manage_status;
        $sort = $this->request->input('sort', '1');
        $sort = $sort == 2 ? 'vote_num DESC,id DESC' : ($sort == 3 ? 'review_score DESC,id DESC' : 'id DESC'); //vote_num ASC,id ASC 解决点赞量全为0时，数据错乱问题

        $status = empty($status) ? [1, 2, 3] : [$status];
        $res = $this->model->lists($con_id, $type, $group_id, null, $type_id, $keywords,  $status, $except_ids, $is_review_score, $is_add_ebook, $is_violate, $is_show, $start_time, $end_time, $sort, $except_database_id, $score_manage_id, $score_manage_status, $limit);
        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $competiteActivityGroupModel = new CompetiteActivityGroup();
        $competiteActivityWorksType = new CompetiteActivityWorksType();
        $userInfoModel = new UserInfo();
        $ids = [];
        foreach ($res['data'] as $key => $val) {
            $ids[] = $val['id'];
            $res['data'][$key]['type_name'] = $competiteActivityWorksType->where('id', $val['type_id'])->value('type_name');

            if ($val['type'] == 1) {
                $user_info = $userInfoModel->getWechatField($val['user_id'], ['head_img', 'nickname']);
                $res['data'][$key]['head_img'] = $user_info['head_img'];
                $res['data'][$key]['nickname'] = $user_info['nickname'];
            } else {
                $group_info = $competiteActivityGroupModel->getGroupNameByGroupId($val['group_id'], ['name', 'img']);
                $res['data'][$key]['head_img'] = $group_info['img'];
                $res['data'][$key]['group_name'] = $group_info['name'];
                $res['data'][$key]['nickname'] = $group_info['name'];//和上面保持一致
            }

            //判断自己对当前作品的审核状态
            $res['data'][$key]['self_status'] = $this->model->getSelfCheckStatus($val['id'], $val);
            //判断自己对当前作品的评审打分状态
            $res['data'][$key]['review_score_status'] = $this->model->getSelfReviewScoreStatus($val['id'], $val);
        }
        //设置表头
        $row = [[
            "id" => '序号',
            "title" => '作品名称',
            "type_name" => '作品类型',
            "nickname" => '账号昵称',
            "serial_number" => '作品编号',
            "vote_num" => '票数',
            "review_score" => '总分',
            "average_score" => '平均分',
            "works_score_string" => '打分情况',
            "browse_num" => '浏览量',
            "status" => '状态',
            "username" => '作者',
            "id_card" => '身份证',
            "tel" => '电话号码',
            "reader_id" => '读者证',
            "unit" => '单位名称',
            "wechat_number" => '微信号',
            "adviser" => '指导老师',
            "adviser_tel" => '指导老师联系方式',
            "age" => '年龄',
            "school" => '学校',
            "participant" => '参赛者',
            "original_work" => '原著',
            "is_show" => '是否显示',
            "create_time" => '上传时间',
        ]];
        $title = '大赛作品导出列表-' . date('YmdHis');
        
        //执行导出
        $data = $this->setData($res['data'], true); //要导入的数据
        return $this->exportData($data, $title, $row);
    }

    /**
     * 处理 数据
     * @param $is_view_title 是否显示活动标题
     */
    public function setData($data)
    {
        $excel_data = [];
        /*设置excel内容*/
        foreach ($data as $key => $val) {
            $user_type = $val['type'] == 1 ? '个人' : '团队';
            $excel_data[$key]['id'] = $key + 1;
            $excel_data[$key]['title'] = $val['title'];
            $excel_data[$key]['type_name'] = $val['type_name'];
            $excel_data[$key]['nickname'] = $val['nickname'] . "(" . $user_type . ")";
            $excel_data[$key]['serial_number'] = $val['serial_number'];
            $excel_data[$key]['vote_num'] = $val['vote_num'];
            $excel_data[$key]['review_score'] = $val['review_score'];
            $excel_data[$key]['average_score'] = $val['average_score'];
            $excel_data[$key]['works_score_string'] = $val['works_score_string'];
            $excel_data[$key]['browse_num'] = $val['browse_num'];
            $excel_data[$key]['status'] = $val['status'] == 1 ? '已通过' : ($val['status'] == 2 ? '已拒绝(' . $val['reason'] . ')' : '审核中');
            $excel_data[$key]['username'] = $val['username'];
            $excel_data[$key]['id_card'] = "\t" . $val['id_card'];
            $excel_data[$key]['tel'] = "\t" . $val['tel'];
            $excel_data[$key]['reader_id'] = "\t" . $val['reader_id'];
            $excel_data[$key]['unit'] = $val['unit'];
            $excel_data[$key]['wechat_number'] = $val['wechat_number'];
            $excel_data[$key]['adviser'] = $val['adviser'];
            $excel_data[$key]['adviser_tel'] = $val['adviser_tel'];
            $excel_data[$key]['age'] = $val['age'];
            $excel_data[$key]['school'] = $val['school'];
            $excel_data[$key]['participant'] = $val['participant'];
            $excel_data[$key]['original_work'] = $val['original_work'];
            $excel_data[$key]['is_show'] = $val['is_show'] == 1 ? '显示' : '未显示';
            $excel_data[$key]['create_time'] = $val['create_time'];
        }
        return $excel_data;
    }


    /**
     * 导出数据
     *
     * @param [type] $data
     * @return void
     */
    public function exportData($data, $title, $row)
    {
        $header = $row; //导出表头
        $excel = new Export($data, $header, $title);
        $excel->setColumnWidth(['A' => 10, 'B' => 30, 'C' => 30, 'D' => 20, 'E' => 20, 'F' => 15, 'G' => 15, 'H' => 15, 'I' => 30, 'J' => 20, 'K' => 20, 'L' => 20, 'M' => 20, 'N' => 20, 'O' => 20, 'P' => 20, 'Q' => 20, 'R' => 20, 'S' => 20, 'T' => 20, 'U' => 20, 'V' => 15, 'W' => 15, 'X' => 15, 'Y' => 20]);
        $excel->setRowHeight([1 => 30]);
        // $excel->setFreezePane('A2');
        // $excel->setFont(['A1:Z1265' => '宋体']);
        // $excel->setFontSize(['A1:I1' => 14,'A2:Z1265' => 10]);
        // $excel->setBold(['A1:Z2' => true]);
        // $excel->setBackground(['A1:A1' => '808080','C1:C1' => '708080']);
        // $excel->setMergeCells(['A1:I1']);
        // $excel->setBorders(['A2:D5' => '#000000']);
        return Excel::download($excel, $title . '.xlsx');
    }
}
